<script setup lang="ts">
import navData from "../../utils/route.data"
import { childPathItem } from '../../types/header'
import {ref,reactive,watch} from "vue"
import useHeaderStore from '@/store/modules/useHeader'
import {useRoute, useRouter} from "vue-router";
import { useWindowScroll } from '@vueuse/core'
const route = useRoute()
const router = useRouter()

const headerStore = useHeaderStore()
let navDataList = ref<childPathItem[]>(navData)

let {y : top} = useWindowScroll() // 这里的top会实时改变 使用vueuse方法


function updateMenuChecked(currentPath:string) {
  // 忽略路由参数部分
  const pathWithoutParams = currentPath.split('?')[0];
  // 递归检查菜单项和子菜单项，设置 checked 属性并高亮父级节点
  const updateItem = (items) => {
    items.forEach(item => {
      const pathMatches = item.path === pathWithoutParams;
      item.checked = pathMatches; // 当前菜单项是否匹配当前路径
      if (pathMatches) {
        // 如果当前菜单项匹配当前路径，继续向上查找父级节点并标记为选中
        markParentChecked(item);
      }
      if (item.children) {
        updateItem(item.children); // 递归检查子菜单项
      }
    });
  };
  updateItem(navDataList.value);
}
function markParentChecked(item) {
  // 递归向上查找父级节点并标记为选中
  const parent = findParent(navDataList.value, item);
  if (parent) {
    parent.checked = true;
    // 继续向上查找更高级别的父级节点
    markParentChecked(parent);
  }
}
function findParent(items, target) {
  // 在菜单数据中查找目标节点的父级节点
  for (let item of items) {
    if (item.children) {
      for (let child of item.children) {
        if (child === target) {
          return item;
        }
      }
      const parent:any = findParent(item.children, target);
      if (parent) {
        return parent;
      }
    }
  }
  return null;
}



/* 初始化元素的选中状态 */
function initNavData() {
  navDataList.value.forEach((item) => {
    item.checked = false
    if(item.children) {
      item.children.forEach((child) => {
        child.checked = false
        child.pid = item.id
      })
    }
  })
  navDataList.value[0].checked = true
}
initNavData()


// 点击导航
function navClick(navItem:childPathItem){
  router.push(navItem.path)
}

function subNaveClick(navItem:childPathItem,subItem:childPathItem){
  router.push(subItem.path)
}

function flattenMenu(menuItems: childPathItem[]): childPathItem[] {
  const flattenedMenu: childPathItem[] = [];

  menuItems.forEach(item => {
    flattenedMenu.push(item);
    if (item.children) {
      flattenedMenu.push(...flattenMenu(item.children));
    }
  });
  return flattenedMenu;
}

let flattNavData = flattenMenu(navDataList.value) // 扁平化处理之后的数据
let activedId = ref<number>(0) // 当前选中激活的id

watch(() => route.path,(newVal) => {
  if(newVal!=='/') {
    headerStore.switchIsBlack(false)
  }else if(newVal == '/'){
    headerStore.switchIsBlack(true)
  }
  /* 不管什么先去寻找符合当前路径的path */
  let findPathItem = flattNavData.find(item => {
    if(item.path == route.path) {
      return item
    }
  })
  console.log('findPathItem',findPathItem)
  if(findPathItem) {
    let {pid,id} = findPathItem
    if(pid !== 0) {
      /*说明当前跳转的不是父级  ---- 需要根据pid查询到父亲id */
      let parentItem = flattNavData.find( v => v.id == pid) as childPathItem
      activedId.value = parentItem.id
    }else {
      activedId.value = findPathItem.id
    }
  }

},{immediate:true})

// 将嵌套的菜单数据扁平化
const flattenedMenuData = flattenMenu(navData);

function findItemById(items: childPathItem[], targetId: number): childPathItem | null {
  for (const item of items) {
    if (item.id === targetId) {
      return item;
    }
    if (item.children) {
      const foundInChildren = findItemById(item.children, targetId);
      if (foundInChildren) {
        return foundInChildren;
      }
    }
  }
  return null;
}



</script>
<template>
  <div class="jc-header" :class="[(top > 0 && route.path!=='') ? 'white-bg-color' : '']">
    <div class="jc-header-wrap jc-center-width">
      <div class="jc-header-inner" :class="[headerStore.isBlack ? 'black-title' : '']">
      <div class="jc-header-logo">
        <img src="https://img.zcool.cn/community/01c5175d175512a8012051cdec0840.png@2o.png" class="jc-logo" alt="logo" srcset="">
        <div class="jc-logo-text jc-m-l-10">
          <p class="jc-title jc-ft-18">京城贸易</p>
          <p class="jc-title-py jc-ft-15">JCMY</p>
        </div>
      </div>
      <div class="jc-header-nav">
        <ul class="right-nav">
          <li
            class="nav-item"
            v-for="(navItem,navIndex) in navDataList"
            :key="navItem.id"
            @click="navClick(navItem)"
          >
            <p class="nav-link"  :class="[ activedId == navItem.id ? 'active-item' : '']">
              {{ navItem.title }}
              <span v-if="navItem.children" class="iconfont icon-xiangxia"></span>
            </p>

            <ul v-if="navItem.children" class="sub-nav">
                <li class="sub-nav-item"
                  v-for="(subItem,subIndex) in navItem.children"
                  @click="subNaveClick(navItem,subItem)"
                >
                  <a href="javascript:void(0);">{{ subItem.title }}</a>
                </li>
            </ul>
          </li>
        </ul>
      </div>
    </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.jc-header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 33;
  background-color: transparent;
  .jc-header-wrap {
    padding: 20px 0px;
    margin: 0 auto;
    color: var(--jc-heading-color);
    .jc-header-inner {
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .jc-header-logo {
        display: flex;
        align-items: center;
        .jc-logo {
          width: 40px;
          height: 40px;
          object-fit: cover;
        }
        .jc-logo-text {
          font-size: 16px;
          display: flex;
          //flex-direction: column;
          justify-content: space-between;
          .jc-title {
            font-weight: bold;
            color: var(--jc-heading-color);
          }
          .jc-title-py {
            margin-left: 10px;
            //font-style: oblique;
            text-align: center;
            color: var(--jc-heading-color);
            opacity: .8;
            font-weight: 400;
          }
        }
      }

      .jc-header-nav {
        color: var(--jc-heading-color);
        .right-nav {
          display: flex;
          align-items: center;
          .nav-item {
            position: relative;
            cursor: pointer;
            padding: 12px 0px;
            color: var(--jc-heading-color);
            & :hover {
              color: var(--jc-color-primary);
            }
            &:has(.active-item):not(:has(.sub-nav))::after {
              display: block;
            }
            &:not(:has(.sub-nav))::after {
              display: none;
              content: "";
              width: 6px;
              height: 6px;
              border-radius: 50%;
              border: 1px solid var(--jc-color-primary);
              position: absolute;
              left: 50%;
              bottom: 0px;
              transform: translateX(-50%);
            }
            &:hover::after {
              display: block;
            }
            &:hover .nav-link {
              color: var(--jc-color-primary);
            }
            &:hover .sub-nav {
              display: block;
            }
            .nav-link {
              // transition: .2s all ease-in-out;
            }
            .sub-nav {
              display: none;
              position: absolute;
              width: max-content;
              left: 50%;
              transform: translateX(-50%);
              top: calc(12px + 20px + 10px);
              padding: 10px 15px;
              background-color: #fff;
              opacity: 1;
              box-shadow: 0 0 60px rgba(0,0,0,.1);
              .sub-nav-item {
                position: relative;
                padding: 8px 2px;
                &::after {
                  position: absolute;
                  content: "";
                  width: 0%;
                  height: 1px;
                  transition: .5s all ease;
                  background-color: var(--jc-color-primary);
                  left: 0px;
                  bottom: 0px;
                }
                &:hover::after {
                  width: 100%;
                }
                // &:hover {
                //   display: block;
                // }
                &:hover a {
                  color: var(--jc-color-primary);
                }
              }
            }
          }
        }
      }
    }

    // 白色文本
    .black-title {
      .jc-header-logo {
        .jc-logo-text {
          .jc-title {
            color: var(--jc-color-text-primary);
          }
          .jc-title-py {
            color: var(--jc-color-text-primary);
          }
        }
      }

      .jc-header-nav {
        color: var(--jc-color-text-primary);
        .right-nav {
          .nav-item {
            color: var(--jc-color-text-primary);
            & :hover {
              color: var(--jc-color-text-primary);
            }
            &:not(:has(.sub-nav))::after {
              border: 1px solid var(--jc-color-text-primary);
            }
            &:hover .nav-link {
              color: var(--jc-color-text-primary);
            }
            .sub-nav {
              .sub-nav-item {
                &::after {
                  background-color: var(--jc-color-primary);
                }
                &:hover a {
                  color: var(--jc-color-primary);
                }
              }
            }
          }
        }
      }
    }
  }
}

.white-bg-color {
  background-color: #fff;
}


::v-deep .nav-item {
  .nav-link {
    padding: 0px 20px;
    color: var(--jc-heading-color);
  }
  .active-item {
    color: var(--jc-color-primary);
  }
}

::v-deep .black-title {
  .nav-item {
    .nav-link {
      padding: 0px 20px;
      color: var(--jc-color-text-primary);
    }
    .active-item {
      color: var(--jc-color-text-primary);
    }
  }
}
</style>
